package com.minelx.woods.server.controller;

import com.alibaba.fastjson.JSONObject;
import com.minelx.woods.server.common.JWToken;
import com.minelx.woods.server.dao.UserDTO;
import com.minelx.woods.server.entity.Users;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

import static org.springframework.http.ResponseEntity.ok;

@RestController
public class AuthController {
	private final Users users;

	public AuthController(Users users) {
		this.users = users;
	}

	@PostMapping("/auth/token")
	ResponseEntity<?> createToken(@RequestBody JSONObject body) {
		String user = body.getString("user");
		UserDTO userValues = users.id(user).values();

		String password = body.getString("password");
		if (userValues.getPassword().equals(password)) {
			return ok(Map.of("token", JWToken.create(user)));
		} else {
			return ResponseEntity.noContent().build();
		}
	}
}
